package com.example.myapplication;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MyThread extends Thread{
    private Handler handler;
    private ArrayList<Map> list = new ArrayList<>();
    public MyThread(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            URL url = new URL("https://www.wanandroid.com/article/list/0/json");
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("GET");
            coon.setConnectTimeout(5000);
            if (coon.getResponseCode() == 200){
                InputStream inputStream = coon.getInputStream();
                InputStreamReader input = new InputStreamReader(inputStream);
                BufferedReader bf = new BufferedReader(input);
                StringBuffer sbf = new StringBuffer();
                String n;
                while ((n = bf.readLine())!=null){
                    sbf.append(n);
                }
                String str = sbf.toString();
                JSONObject jsonObject = new JSONObject(str);
                if((jsonObject.optInt("errorCode")==0)){
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray array = data.getJSONArray("datas");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        String title = object.optString("title");
                        Map<String, String> map = new HashMap<>();
                        map.put("title", title);
                        list.add(map);
                    }
                }
                Message mes = new Message();
                mes.obj = list;
                handler.sendMessage(mes);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}